package com.xhp.xtool.util.redis;

import com.xhp.xtool.domain.RedisDto;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtil {

    private static int maxIdle = 30;
    private static int maxTotal = 100;
    private static int maxWaitMillis = 2000;
    private static boolean testOnBorrow = true;

    private static volatile JedisPool jedisPool = null;

    private JedisPoolUtil() {
    }

    public static JedisPool getJedisPoolInstance(RedisDto redisDto) {
        try {
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            poolConfig.setMaxIdle(maxIdle);
            poolConfig.setMaxTotal(maxTotal);
            poolConfig.setMaxWaitMillis(maxWaitMillis);
            poolConfig.setTestOnBorrow(testOnBorrow);
            jedisPool = new JedisPool(poolConfig, redisDto.getHost(), redisDto.getPort(), 3000, redisDto.getPassword());
        } catch (Exception e) {
            e.printStackTrace();
            if (jedisPool != null) {
                jedisPool.close();
            }
        }
        return jedisPool;
    }

    private static JedisPool getJedisPoolInstance() {
        if (null == jedisPool) {
            return null;
        }
        return jedisPool;
    }

    /**
     * 获取实例
     *
     * @return
     * @author Cheng
     * @date 2020年8月13日 上午10:29:08
     */
    public static Jedis getJedis() {
        Jedis jedis = null;
        try {
//			if (jedisPool != null) {
            jedis = getJedisPoolInstance().getResource();
//			}
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            returnResource(jedis);
        }
        return jedis;
    }

    /**
     * 归还资源
     *
     * @param jedis
     * @author Cheng
     * @date 2020年8月13日 上午10:29:03
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null && jedisPool != null) {
            jedis.close();
        }
    }

}
